package com.ssyc.gsk_master.activity;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.gsk_master.R;
import com.ssyc.gsk_master.adapter.RedTemplateAdapter;
import com.ssyc.gsk_master.bean.RedTemplateInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 红包皮肤定制
 */
public class MasterRedPacageTemplateActivity extends Activity implements View.OnClickListener {

    //正常加载
    public static final int NORMAL = 0X110;

    //下拉刷新
    public static final int PULLTOREFRESH = 0X120;

    //返回
    private LinearLayout llBack;

    //加载
    private LinearLayout llLoading;

    //空数据
    private LinearLayout llEmpty;

    //刷新控件
//    private PullToRefreshLayout ptrl;

    //GridView控件
    private GridView gv;

    //数据集合
    private List<RedTemplateInfo.SkinsBean> oldDatas;

    //屏幕宽度
    private int screenWidth;
    private RedTemplateAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.master_activity_red_package_template);

        //设置状态栏颜色
        setBar();

        //初始化View
        initViews();

        //设置监听
        initListener();

        //初始化GridView
        initGv();

        //请求服务器获取数据
        http(NORMAL);
    }


    /**
     * 初始化View
     */
    private void initViews() {
        llBack = findViewById(R.id.ll_back);
        llLoading = findViewById(R.id.ll_loading);
        llEmpty = findViewById(R.id.ll_empty);
//        ptrl = findViewById(R.id.refresh_view);
        gv = findViewById(R.id.gv);
    }

    /**
     * 设置监听方法
     */
    private void initListener() {
        llBack.setOnClickListener(this);
//        ptrl.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onPullDownToRefresh() {
//                http(PULLTOREFRESH);
//            }
//
//            @Override
//            public void onPullUpToRefresh() {
//
//            }
//        });
    }

    /**
     * 初始化GridView的方法
     */
    private void initGv() {
        //获取屏幕宽度
        //获取屏幕宽度
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
        oldDatas = new ArrayList<RedTemplateInfo.SkinsBean>();
        adapter = new RedTemplateAdapter(this, oldDatas,
                R.layout.master_item_gb_redpackage_template, screenWidth);
    }


    /**
     * 网络请求的方法
     */
    private void http(final int method) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "11");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("schoolId", "20001");
//        map.put("schoolId", AccountUtils.getAccount(getActivity()));
        map.put("platform", "8");


        HttpUtils.post(HttpAdress.REDPACKAGE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {

                RedTemplateInfo info = null;

                try {
                    info = GsonUtil.jsonToBean(response, RedTemplateInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                Log.i("test", "红包皮肤"+ response);

                if (null != info) {
                    if ("1".equals(info.getState())) {
                        //返回成功
                        List<RedTemplateInfo.SkinsBean> skins = info.getSkins();

                        if (null != skins && skins.size() != 0) {
                            //证明有列表数据,更新主界面

                            if (method == NORMAL) {
                                //正常请求
                                if (llLoading != null) {
                                    llLoading.setVisibility(View.GONE);
                                }
                                initGv();
                                oldDatas.addAll(skins);
                                gv.setAdapter(adapter);
                                Log.i("test","run");
                            } else {
                                //下拉刷新
                                oldDatas.clear();
                                oldDatas.addAll(skins);
//                                        ptrl.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
                                adapter.notifyDataSetChanged();
                            }


                        } else {
                            //证明没有数据,显示空视图,隐藏加载框
                            if (method == NORMAL) {
                                //正常加载
                                if (llLoading != null) {
                                    llLoading.setVisibility(View.GONE);
                                }
                                if (llEmpty != null) {
                                    llEmpty.setVisibility(View.VISIBLE);
                                }
                                gv.setAdapter(adapter);
                            } else {
                                //下拉刷新
//                                ptrl.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
                                adapter.notifyDataSetChanged();

                            }
                        }


                    } else {
                        //返回错误
                        UiUtils.Toast("服务器返回异常,状态码是:" + info.getState(), false);
                        Log.i("test", "服务器返回异常,状态码是:" + info.getState());
                    }
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });


//        OkHttpClient mOkHttpClient = new OkHttpClient();
//        FormEncodingBuilder builder = new FormEncodingBuilder();
//        builder.add("type", "11");
//        builder.add("schoolId", SPUtil.getString(this, "schoolId", ""));
//        builder.add("c", SPUtil.getString(this, "account", ""));
//        builder.add("role", "3");
//        Request request = new Request.Builder()
//                .url(Constant.SERVER_URL+"RedPacketMsg").post(builder.build())
//                .build();
//
//        mOkHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        //请求失败,主线程更新UI操作
//                        if (llLoading != null) {
//                            llLoading.setVisibility(View.GONE);
//                        }
//                        Toast.makeText(RedPacageTemplateActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//
//            @Override
//            public void onResponse(Response arg0) throws IOException {
//                try {
//                    //请求成功
//                    //获取服务器返回的json数据
//                    String json = arg0.body().string();
//                    if (!TextUtils.isEmpty(json)) {
//                        RedTemplateInfo redTemplateInfo = GsonUtil.jsonToBean(json, RedTemplateInfo.class);
//                        //获取列表数据
//                        final List<RedTemplateInfo.SkinsBean> skins = redTemplateInfo.getSkins();
//                        if (null != skins && skins.size() != 0) {
//                            //证明有列表数据,更新主界面
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    if (method == NORMAL) {
//                                        //正常请求
//                                        if (llLoading != null) {
//                                            llLoading.setVisibility(View.GONE);
//                                        }
//                                        oldDatas.addAll(skins);
//                                        gv.setAdapter(adapter);
//                                    } else {
//                                        //下拉刷新
//                                        oldDatas.clear();
//                                        oldDatas.addAll(skins);
//                                        ptrl.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
//                                        adapter.notifyDataSetChanged();
//                                    }
//                                }
//                            });
//                        } else {
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    //证明没有数据,显示空视图,隐藏加载框
//                                    if (method == NORMAL) {
//                                        //正常加载
//                                        if (llLoading != null) {
//                                            llLoading.setVisibility(View.GONE);
//                                        }
//                                        if (llEmpty != null) {
//                                            llEmpty.setVisibility(View.VISIBLE);
//                                        }
//                                        gv.setAdapter(adapter);
//                                    } else {
//                                        //下拉刷新
//                                        ptrl.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
//                                    }
//                                }
//                            });
//                        }
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.ll_back) {
            //返回
            finish();
        }
    }


    /**
     * 设置沉浸状态栏的方法,需要在setContentView()之后调用
     */
    private void setBar() {
        //兼容5.0+，状态栏设置透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else
            //为了沉浸式状态栏 4.4以上才有
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
    }

}
